import CheckOutlined from "@ant-design/icons/CheckOutlined"
import { Option, Product, ProductVariant } from "@mallfoundry/catalog"
import { Button, Card, Checkbox, Col, Divider, Form, Input, InputNumber, Row, Select } from "antd"
import * as _ from "lodash"
import * as React from "react"
import { useEffect, useRef, useState } from "react"
import { useHistory } from "react-router-dom"
import Display from "../../components/display"
import { useCollections } from "../../hooks/collection"
import ProductBody from "./product-body"
import ProductFormRegion from "./product-form-region"
import ProductFormSteps, { ProductFormStep } from "./product-form-steps"
import classes from "./product-form.module.scss"
import ProductImages from "./product-images"
import ProductOptions from "./product-options"
import ProductVariants from "./product-variants"
import ProductVariantsImages from "./product-variants-images"

interface ProductFormProps {
  product: Product;
  loading?: boolean;
  onFinish?: (product: Product) => void
}

export default function ProductForm(props: ProductFormProps) {
  const history = useHistory()
  const [product, setProduct] = useState(props.product)
  const [step, setStep] = useState(0)
  const { elements: collections } = useCollections({ storeId: props.product.storeId })
  const [form] = Form.useForm()
  const collectionIdsOptionsRef = useRef(null)


  useEffect(() => {
    setProduct(props.product)
  }, [props.product])

  // 设置商品表单数据
  useEffect(() => {
    form.setFieldsValue(product)
  }, [form, product])

  function onFinish(values: any) {
    if (_.isFunction(props.onFinish)) {
      props.onFinish(_.assign(new Product(), product, values))
    }
  }

  function onChangeOptions(options: Option[]) {
    setProduct(_.assign(new Product(), product, { options }))
  }

  function handleChangeVariants(variants: ProductVariant[]) {
    setProduct(_.assign(new Product(), product, { variants }))
  }

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 2 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 20 },
    },
  }

  const formInputItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 2 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 8 },
    },
  }

  return (
    <Form className={classes.ProductForm} {...formItemLayout} form={form} scrollToFirstError onFinish={onFinish}>
      <Row gutter={[0, 16]}>
        <Col span={24}>
          <Card>
            <ProductFormSteps current={step} onChange={setStep}>
              <ProductFormStep>1. 编辑基本信息</ProductFormStep>
              <ProductFormStep>2. 编辑商品详情</ProductFormStep>
            </ProductFormSteps>
            <Display show={step === 0}>
              <ProductFormRegion title="商品类型">
                <Form.Item>
                  <Button className={classes.ProductTypeRadio}>
                    <div>实物商品</div>
                    <div className={classes.ProductTypeRadioDescription}>（物流发货）</div>
                    <div className={classes.ProductTypeRadioSelected}>
                      <div className={classes.ProductTypeRadioChecked}>
                        <CheckOutlined/>
                      </div>
                    </div>
                  </Button>
                </Form.Item>
              </ProductFormRegion>
              <ProductFormRegion title="基本信息">
                <Form.Item name="name" label="商品名" {...formInputItemLayout}
                           rules={[{ required: true, message: "请输入商品名" }]}>
                  <Input placeholder="请输入商品名称"/>
                </Form.Item>
                {/* <Form.Item {...formInputItemLayout} label="商品类目" extra="准确选择商品类目有助于完善商品信息与数据分析">
                <Button>选择商品类目</Button>
              </Form.Item>*/}
                <Form.Item name="description" label="商品描述" {...formInputItemLayout}>
                  <Input.TextArea placeholder="建议60字以内，未填将根据商品标题自动生成" rows={3}/>
                </Form.Item>
                <Form.Item label="商品图" extra="建议尺寸：800*800像素，你可以拖拽图片调整顺序，最多上传10张">
                  <ProductImages imageUrls={product.imageUrls as string[]}
                                 onChange={imageUrls => setProduct(_.assign(new Product(), product, { imageUrls }))}/>
                </Form.Item>
                <div ref={collectionIdsOptionsRef}/>
                <Form.Item name="collections" label="商品分组" {...formInputItemLayout}>
                  <Select mode="multiple" placeholder="请选择分组"
                          getPopupContainer={() => collectionIdsOptionsRef.current as unknown as HTMLSelectElement}>
                    {
                      _.map(collections, collection =>
                        <Select.Option key={collection.id} value={collection.id as string} children={collection.name}/>)
                    }
                  </Select>
                </Form.Item>
              </ProductFormRegion>
              <ProductFormRegion title="价格库存">
                <Form.Item label="规格选项">
                  <Card size="small">
                    <ProductOptions options={product.options as Option[]} onChange={onChangeOptions}/>
                    <Divider/>
                    <ProductVariants options={product.options as Option[]}
                                     variants={product.variants as ProductVariant[]}
                                     onChange={handleChangeVariants}/>
                  </Card>
                </Form.Item>
                <Form.Item
                  label="规格图片">
                  <Card size="small">
                    <ProductVariantsImages product={product} onChange={setProduct}/>
                  </Card>
                </Form.Item>
              </ProductFormRegion>
              <ProductFormRegion title="物流信息">
                <Form.Item label="配送方式">
                  <Checkbox.Group value={["A"]}>
                    <Checkbox value="A">快递</Checkbox>
                    <Checkbox value="B" disabled>同城配送</Checkbox>
                    <Checkbox value="C" disabled>到店自提</Checkbox>
                  </Checkbox.Group>
                </Form.Item>
                <Form.Item label="快递运费" name="fixedShippingCost">
                  <InputNumber style={{ width: "200px" }} min={0}
                               formatter={value => `¥ ${value}`}
                               parser={value => _.isUndefined(value) ? "" : value.replace(/¥\s?/g, "")}/>
                </Form.Item>
              </ProductFormRegion>
            </Display>
            <Display show={step === 1}>
              <ProductBody product={product}/>
            </Display>
          </Card>
        </Col>
      </Row>
      <Card>
        <Row gutter={16} justify="center">
          <Col>
            <Button type="primary" htmlType="button" loading={props.loading}
                    onClick={() => form.submit()}>保存</Button>
          </Col>
          <Col><Button onClick={() => history.goBack()}>取消</Button></Col>
        </Row>
      </Card>
    </Form>
  )
}
